import { store } from "@/store"
import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'
import { showError } from '@/utils/msg-show'
import { getPageApi } from '@/api/user/vip'
import { getPageApi as getPageOfUserApi } from '@/api/user/list'


export const useUserVipStore = defineStore("UserVip", () => {

	const isZero = ref(true)
	const dataList = ref<any[]>([])
	const query = reactive<any>({
		pageNum: 1,
		pageSize: 10,
		totalSize: 0,
        nickename: '',
        userId: '',
	})
    
    const keyword = ref()
    const userDataList = ref<any[]>([])

    /** 分页获取 */
	async function getPage() {
		await getPageApi(query).then( (res: any) => {
			query.totalSize = res.data.total
			if(query.pageNum == 1){
				dataList.value = res.data.list
			}else{
				dataList.value = dataList.value.concat(res.data.list)
			}
		}).catch(err => {
			showError(err.msg || err.errMsg || err)
		})
	}
    
    // 更新
    function update(){
         const pageSize = query.pageNum * query.pageSize 
         getPageApi({ ...query, pageNum: 1, pageSize }).then( (res: any) => {
			query.totalSize = res.data.total
			dataList.value = res.data.list
		}).catch(err => {
			showError(err.msg || err.errMsg || err)
		})
    }

    /** 用户搜索 */
    async function getUser(){
        await getPageOfUserApi({ keyword: keyword.value, pageSize: 30}).then( (res: any) => {
			userDataList.value = res.data.list
		}).catch(err => {
			showError(err.msg || err.errMsg || err)
		})
    }

	/** 初始化 */
	async function init() {
		if (isZero.value) {
			await getPage()
			isZero.value = false
		}
	}
    
    /** 初始化用户 */
    function initUser(){
        if(userDataList.value.length == 0){
            getUser()
        }
    }

	return {
		init, initUser, getPage, getUser, update,
		query, dataList, keyword, userDataList
	}

})

export function useUserVipStoreHook() {
	return useUserVipStore(store);
}